package cn.gp.chatclient.ui.panel;

import cn.gp.chatclient.config.ClientConfig;
import cn.gp.chatclient.model.MessageVo;
import cn.gp.chatclient.model.UserVo;
import cn.gp.chatclient.websocket.ChatWebSocketClient;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class ChatPanel extends JPanel {
    private final UserVo currentUser;
    private UserVo currentContact;
    private final JTextArea chatArea;
    private final JTextField messageField;
    private final JLabel titleLabel;
    private final ObjectMapper objectMapper = new ObjectMapper();
    private ChatWebSocketClient webSocketClient;
    private static final Logger log = LoggerFactory.getLogger(ChatPanel.class);
    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public ChatPanel(UserVo currentUser) {
        this.currentUser = currentUser;
        setLayout(new BorderLayout());
        setBackground(Color.WHITE);

        // 创建标题面板
        JPanel titlePanel = new JPanel(new BorderLayout());
        titlePanel.setBackground(Color.WHITE);
        titlePanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        titleLabel = new JLabel("聊天");
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 16));
        titlePanel.add(titleLabel, BorderLayout.WEST);
        add(titlePanel, BorderLayout.NORTH);

        // 创建聊天区域
        chatArea = new JTextArea();
        chatArea.setEditable(false);
        chatArea.setLineWrap(true);
        chatArea.setWrapStyleWord(true);
        chatArea.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        chatArea.setBackground(new Color(240, 240, 240));
        JScrollPane chatScrollPane = new JScrollPane(chatArea);
        chatScrollPane.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createEmptyBorder(0, 0, 10, 0),
                BorderFactory.createLineBorder(Color.LIGHT_GRAY)
        ));
        add(chatScrollPane, BorderLayout.CENTER);

        // 创建输入面板
        JPanel inputPanel = new JPanel(new BorderLayout());
        inputPanel.setBackground(Color.WHITE);
        inputPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));

        messageField = new JTextField();
        messageField.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        messageField.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(Color.LIGHT_GRAY),
                BorderFactory.createEmptyBorder(5, 5, 5, 5)
        ));
        messageField.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                    sendMessage();
                }
            }
        });

        JButton sendButton = new JButton("发送");
        sendButton.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        sendButton.setFocusPainted(false);
        sendButton.setBackground(new Color(0, 120, 215));
        sendButton.setForeground(Color.WHITE);
        sendButton.setBorder(new EmptyBorder(5, 15, 5, 15));
        sendButton.addActionListener(e -> sendMessage());

        inputPanel.add(messageField, BorderLayout.CENTER);
        inputPanel.add(sendButton, BorderLayout.EAST);
        add(inputPanel, BorderLayout.SOUTH);

        // 初始化WebSocket客户端
        initializeWebSocket();
    }

    private void initializeWebSocket() {
        String wsUrl = ClientConfig.getChatWebSocketUrl(currentUser.getId());
        webSocketClient = new ChatWebSocketClient(wsUrl);
        webSocketClient.setMessageHandler(this::handleMessage);
        webSocketClient.connect();
        
        // 等待连接建立
        new Thread(() -> {
            int retryCount = 0;
            while (!webSocketClient.isOpen() && retryCount < 5) {
                try {
                    Thread.sleep(1000);
                    retryCount++;
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    break;
                }
            }
            if (!webSocketClient.isOpen()) {
                SwingUtilities.invokeLater(() -> {
                    JOptionPane.showMessageDialog(this,
                        "WebSocket连接失败，请刷新页面重试",
                        "连接错误",
                        JOptionPane.ERROR_MESSAGE);
                });
            }
        }).start();
    }

    public void setCurrentContact(UserVo contact) {
        this.currentContact = contact;
        // 更新标题
        titleLabel.setText(contact.getUsername());
        // 清空聊天区域
        chatArea.setText("");
        // 加载历史消息
        loadChatHistory();
    }

    private void loadChatHistory() {
        if (currentContact != null) {
            log.info("开始加载与用户 {} 的聊天历史", currentContact.getUsername());
            
            // 检查用户ID
            if (currentUser == null || currentUser.getId() == null) {
                log.error("当前用户ID为空");
                SwingUtilities.invokeLater(() -> {
                    JOptionPane.showMessageDialog(this,
                        "无法加载聊天历史：用户未登录",
                        "错误",
                        JOptionPane.ERROR_MESSAGE);
                });
                return;
            }
            
            if (currentContact.getId() == null) {
                log.error("联系人ID为空");
                SwingUtilities.invokeLater(() -> {
                    JOptionPane.showMessageDialog(this,
                        "无法加载聊天历史：联系人信息不完整",
                        "错误",
                        JOptionPane.ERROR_MESSAGE);
                });
                return;
            }
            
            // 从服务器加载历史消息
            webSocketClient.loadChatHistory(currentUser.getId(), currentContact.getId())
                .thenAccept(responseVo -> {
                    if (responseVo.isSuccess()) {
                        List<MessageVo> messages = responseVo.getData();
                        log.info("成功获取聊天历史，消息数量: {}", messages != null ? messages.size() : 0);
                        
                        SwingUtilities.invokeLater(() -> {
                            chatArea.setText(""); // 清空聊天区域
                            if (messages != null && !messages.isEmpty()) {
                                // 反转消息列表，使最早的消息显示在上面
                                for (int i = messages.size() - 1; i >= 0; i--) {
                                    MessageVo message = messages.get(i);
                                    if (message != null && message.getContent() != null) {
                                        // 只在第一条消息（最早的消息）上方显示时间
                                        if (i == messages.size() - 1 && message.getCreateTime() != null) {
                                            String messageDate = DATE_FORMAT.format(message.getCreateTime());
                                            chatArea.append("\n" + messageDate + "\n");
                                        }
                                        
                                        // 根据senderId判断消息发送者
                                        boolean isCurrentUser = message.getSenderId().equals(currentUser.getId());
                                        String senderName = isCurrentUser ? "我" : currentContact.getUsername();
                                        String formattedMessage = String.format("%s: %s",
                                            senderName,
                                            message.getContent());
                                        chatArea.append(formattedMessage + "\n");
                                    }
                                }
                                // 滚动到最新消息
                                chatArea.setCaretPosition(chatArea.getDocument().getLength());
                            } else {
                                chatArea.append("暂无聊天记录\n");
                            }
                        });
                    } else {
                        log.error("加载聊天历史失败: {}", responseVo.getMessage());
                        SwingUtilities.invokeLater(() -> {
                            JOptionPane.showMessageDialog(this,
                                "加载聊天历史失败: " + responseVo.getMessage(),
                                "错误",
                                JOptionPane.ERROR_MESSAGE);
                        });
                    }
                })
                .exceptionally(throwable -> {
                    log.error("加载聊天历史异常", throwable);
                    SwingUtilities.invokeLater(() -> {
                        JOptionPane.showMessageDialog(this,
                            "加载聊天历史异常: " + throwable.getMessage(),
                            "错误",
                            JOptionPane.ERROR_MESSAGE);
                    });
                    return null;
                });
        } else {
            log.warn("当前没有选中的联系人");
        }
    }

    public void refreshChat() {
        if (currentContact != null) {
            loadChatHistory();
        }
    }

    private void handleMessage(String message) {
        try {
            // 检查是否是错误消息
            if (message.startsWith("错误:")) {
                SwingUtilities.invokeLater(() -> {
                    JOptionPane.showMessageDialog(this, message);
                    chatArea.append("系统: " + message + "\n");
                    chatArea.setCaretPosition(chatArea.getDocument().getLength());
                });
                return;
            }

            // 解析消息
            Message chatMessage = objectMapper.readValue(message, Message.class);
            
            // 检查currentContact是否为null
            if (currentContact == null) {
                log.warn("收到消息时currentContact为null，消息内容: {}", chatMessage.getContent());
                SwingUtilities.invokeLater(() -> {
                    chatArea.append("系统: 收到新消息，请选择联系人查看\n");
                    chatArea.setCaretPosition(chatArea.getDocument().getLength());
                });
                return;
            }

            // 只显示发给当前用户的消息
            if (chatMessage.getReceiverId().equals(currentUser.getId())) {
                String senderName = chatMessage.getSenderId().equals(currentContact.getId()) ? 
                    currentContact.getUsername() : "我";
                String formattedMessage = String.format("%s: %s", senderName, chatMessage.getContent());
                SwingUtilities.invokeLater(() -> {
                    chatArea.append(formattedMessage + "\n");
                    chatArea.setCaretPosition(chatArea.getDocument().getLength());
                });
            }
        } catch (Exception e) {
            log.error("消息处理失败", e);
            SwingUtilities.invokeLater(() -> {
                JOptionPane.showMessageDialog(this, "消息处理失败: " + e.getMessage());
            });
        }
    }

    private void sendMessage() {
        String content = messageField.getText().trim();
        if (!content.isEmpty() && currentContact != null) {
            try {
                // 检查WebSocket连接状态
                if (!webSocketClient.isOpen()) {
                    JOptionPane.showMessageDialog(this,
                        "WebSocket连接已断开，正在尝试重新连接...",
                        "连接错误",
                        JOptionPane.WARNING_MESSAGE);
                    // 尝试重新连接
                    webSocketClient.reconnect();
                    return;
                }

                // 创建消息对象
                Message message = new Message();
                message.setSenderId(currentUser.getId());
                message.setReceiverId(currentContact.getId());
                message.setContent(content);
                message.setContentType(1);  // 文本消息
                message.setStatus(0);  // 发送中
                
                // 发送消息
                String messageJson = objectMapper.writeValueAsString(message);
                webSocketClient.send(messageJson);
                
                // 清空输入框
                messageField.setText("");
                
                // 在聊天区域显示消息
                String formattedMessage = String.format("我: %s", content);
                chatArea.append(formattedMessage + "\n");
                chatArea.setCaretPosition(chatArea.getDocument().getLength());
            } catch (Exception e) {
                log.error("发送消息失败", e);
                JOptionPane.showMessageDialog(this, 
                    "发送消息失败: " + (e.getMessage() != null ? e.getMessage() : "未知错误"),
                    "错误",
                    JOptionPane.ERROR_MESSAGE);
            }
        }
    }

    // 消息实体类
    @Data
    @JsonIgnoreProperties(ignoreUnknown = true)
    private static class Message {
        private Long id;
        private Long senderId;
        private Long receiverId;
        private Integer contentType;
        private String content;
        private String fileUrl;
        private Integer status;
        private Date createTime;
        private Date updateTime;
    }
} 